import 'package:FineArt/constants.dart';
import 'package:FineArt/core/api/module_api.dart';
import 'package:FineArt/core/api/user_api.dart';
import 'package:FineArt/core/utils/toast.dart';
import 'package:FineArt/page/Login/components/background.dart';
import 'package:FineArt/page/Signup/signup_screen.dart';
import 'package:FineArt/page/home/tab_home.dart';
import 'package:FineArt/page/home/mainpage.dart';
import 'package:FineArt/utils/log_util.dart';
import 'package:FineArt/utils/platform_util.dart';
import 'package:FineArt/utils/size_config.dart';
import 'package:FineArt/utils/sputils.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

import 'package:FineArt/components/already_have_an_account_acheck.dart';
import 'package:FineArt/components/rounded_button.dart';
import 'package:FineArt/components/rounded_input_field.dart';
import 'package:FineArt/components/rounded_password_field.dart';
import 'package:flutter_svg/svg.dart';

import '../../index.dart';

// ignore: must_be_immutable
class Body extends StatelessWidget {
  final String role;

  Body(this.role, {Key key}) : super(key: key);
  String name;
  String orgNo;

  TextEditingController nameController = new  TextEditingController();
  TextEditingController orgNoController = new  TextEditingController();

  // TapGestureRecognizer _tapGestureRecognizer = new TapGestureRecognizer();
  // TapGestureRecognizer _tapGestureRecognizerPri = new TapGestureRecognizer();
  // ignore: non_constant_identifier_names
  void _login_no_reg() {
    ToastUtils.toast("游客登录");
  }

  void handleLogin(response, context) {
    bool succ = false;
    if (response.code == 200) {
      if (response.token != null) {
        succ = true;
        SPUtils.saveToken("Bearer " + response.token);
        SPUtils.saveUsername(this.name);
        SPUtils.savePassword(this.orgNo);

        UserApi().userInfo().then((res) {
          if (res.code == 200) {
            String uid = res.data.uid;
            SPUtils.saveUID(uid);
            //登录成功
            ModuleApi().modules().then((res) {
              if (res.code == 200) {
                Navigator.of(context)
                    .pushReplacement(MaterialPageRoute(builder: (context) {
                  return TabMainPage("", res.data);
                }));
              } else {
                ToastUtils.toast(res.msg);
              }
            });
          } else {
            ToastUtils.toast(res.msg);
          }
        });
      }
    }

    if (!succ) {
      ToastUtils.error(response.msg);
    }
  }

  _onLogin(context) async {
    String uuid = await PlatformUtil.uuid(name);
    String ver = await PlatformUtil.getVersion();
    SPUtils.saveRole(this.role);
    LogUtil.d("login name: $name org: $orgNo");
    name = nameController.text;
    orgNo = orgNoController.text;
    LogUtil.d("login name: $name org: $orgNo");
    LoginBody body = new LoginBody(nameController.text, orgNoController.text, uuid, 301,ver);

    if (this.role == 'student') {
      UserApi().studentLogin(body).then((response) {
        handleLogin(response, context);
      }).catchError((onError) {
        ToastUtils.error(onError);
      });
    } else {
      UserApi().teacherLogin(body).then((response) {
        handleLogin(response, context);
      }).catchError((onError) {
        ToastUtils.error(onError);
      });
    }
  }

  Widget background(context) {
    Size size = MediaQuery.of(context).size;
    return Background(
      tapPress: () {
        Navigator.pop(context);
      },
      child: SingleChildScrollView(
        padding: EdgeInsets.symmetric(
            vertical: 1, horizontal: getPortraitSWidth(35.5)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              "机构用户登录",
              style: TextStyle(fontSize: setSp(32), color: text_black),
            ),

            Text(
              "新用户登录后将自动创建账号",
              style: TextStyle(fontSize: setSp(16), color: text_black),
            ),
            SizedBox(height: getPortraitSHeight(18.5)),
            RoundedInputField(
              icon: null,
              controller: nameController,
              height: getPortraitSHeight(50),
              text: (name != null) ? name : '',
              hintText: "输入手机号",
              keyType: TextInputType.phone,
              onChanged: (value) {
                name = value;
                LogUtil.d("onChanged name: $name val: $value");
              },
            ),
            SizedBox(height: getPortraitSHeight(8.5)),
            RoundedInputField(
              icon: null,
              controller: orgNoController,
              height: getPortraitSHeight(50),
              keyType: TextInputType.text,
              text: (orgNo != null) ? orgNo : '',
              hintText: "输入机构代码",
              onChanged: (value) {
                orgNo = value;
                LogUtil.d("onChanged orgNo: $orgNo val: $value");
              },
            ),
            SizedBox(height: getPortraitSHeight(41)),
            RoundedButton(
              text: "登录",
              height: getPortraitSHeight(50),
              color: red_main,
              press: () {
                _onLogin(context);
              },
            ),
            SizedBox(
              height: getPortraitSHeight(19),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(200, 0, 20, 0),
              child: InkWell(
                child: Text(
                  "游客登录",
                  style: TextStyle(color: Color(0xFFCACACA)),
                ),
                onTap: _login_no_reg,
              ),
            ),
            // Container(
            //   alignment: Alignment.bottomCenter,
            //   child: Text.rich(
            //       TextSpan(children: [TextSpan(text: "登录代表你已阅读并同意"),
            //       TextSpan(
            //           text: "《用户协议》",
            //           style: TextStyle(
            //               fontSize: 15.0,
            //               color:  Colors.red
            //           ),
            //       recognizer: _tapGestureRecognizer), TextSpan(
            //             text: "《隐私协议》",
            //             style: TextStyle(
            //                 fontSize: 15.0,
            //                 color:  Colors.red
            //             ),
            //             recognizer: _tapGestureRecognizerPri),])),
            // )
            // AlreadyHaveAnAccountCheck(
            //   press: () {
            //     Navigator.push(
            //       context,
            //       MaterialPageRoute(
            //         builder: (context) {
            //           return SignUpScreen();
            //         },
            //       ),
            //     );
            //   },
            // ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    this.name = SPUtils.getUsername();
    this.orgNo = SPUtils.getPassword();

    nameController.text = this.name;
    orgNoController.text = this.orgNo;
    return background(context);
  }
}
